/**************************************************************
          File Name:stdarg.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat Jul 25 09:45:26 2015
***************************************************************/

#include <myarg.h>
#include <stdarg.h>

static char *itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char *p = b;
    if(i < 0)
    {
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

void mysprintf(char *buf, char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    char *s;
    int d;
    char c;
    char digit[256];
    int i, j;

    for(;*fmt; fmt++)
    {
        switch(*fmt)
        {
            case '%':
                if(*(fmt + 1) == 's' || *(fmt + 1) == 'c' || *(fmt + 1) == 'd')
                    break;
                else
                    *buf++ = *fmt;
                break;
            case 's':
                if(*(fmt - 1) == '%')
                {
                    s = va_arg(ap, char *);
                    while(*s)
                        *buf++ = *s++;
                }
                else
                    *buf++ = *fmt;
                break;
            case 'd':
                if(*(fmt - 1) == '%')
                {
                    d = va_arg(ap, int);
                    itoa(d, digit);
                    for(j = 0; digit[j] != '\0'; j++)
                        *buf++ = digit[j];
                }
                else
                    *buf++ = *fmt;
                break;
            case 'c':
                if(*(fmt - 1) == '%')
                {
                    c = (char)va_arg(ap, int);
                    *buf++ = c;
                }
                else
                    *buf++ = *fmt;
                break;
            default:
                *buf++ = *fmt;
        }
    }

    va_end(ap);
}
